<script setup lang="ts">
import { ref, onMounted, onBeforeUpdate, onUpdated } from "vue";
import { emitter } from "../core/eventBus";
import Observer from "../core/observer";

console.log("emitter", emitter);
const b = ref(1);
console.log(b);
const c = ref({ a: 1, b: 2 });
console.log(c);
const count = ref(0);
function createCounter() {
  let i = 0;
  return {
    increment() {
      i++;
      return i;
    },
    decrement() {
      i--;
      return i;
    },
  };
}

let counter = createCounter();
console.log(counter.increment());
console.log(counter.decrement());
function countt() {
  let i = 0;
  function fn() {
    i++;
    console.log(`函数被调用了${i}次`);
  }
  return fn;
}
let fun = countt();
fun();
for (var i = 0; i < 10; i++) {}
console.log(i);
for (let j = 0; j < 10; j++) {
  console.log(j);
}

// let car={
//   'brand':'奔驰',
//   'price':100000,
//   'color':'红色',
// }

let car = {};
let val = 3000;
Object.defineProperty(car, "price", {
  enumerable: true,
  configurable: true,
  get() {
    console.log("price属性被读取了");
    return val;
  },
  set(newVal) {
    console.log("price属性被修改了");
    val = newVal;
  },
});

// 使用示例
interface User {
  name: string;
  age: number;
  hobbies: string[];
}

const user = new Observer<User>({
  name: "Alice",
  age: 25,
  hobbies: ["Reading", "Traveling"],
});

console.log(user);
const method1 = (event: Event) => {
  console.log("方法1执行", event);
};
const method2 = (event: Event) => {
  console.log("方法2执行", event);
};

function logClass(target: any) {
  console.log("logClass执行");
}
// @logClass
class MyClass {
  constructor() {}
}

// --回调函数

function callMe() {
  console.log("I am callback function");
}
function handleClick(name: string, callback: Function) {
  console.log(`点击了${name}`);
  callback();
}
handleClick("hehe", callMe);

let username = ref("hehe");

onBeforeUpdate(() => {
  console.log("beforeUpdate:数据更新前");
});
onUpdated(() => {
  console.log("updated:数据更新后");
});

var a = 1;
function test() {
  var a = 2;
  console.log(a);
  console.log(test2());
  function test2() {
    console.log(a);
    return a;
  }
}
test();

const images = ref<string[]>([]); // 存储图片路径
const imageRefs = ref([]); // 存储图片元素的引用
onMounted(async () => {
  // 使用 import.meta.glob 动态加载图片
  const modules = import.meta.glob("/src/assets/images/*.jpeg");
  setTimeout(() => {
    emitter.on("message", (message) => {
      console.log("订阅消息Received message:", message);
    });
  }, 350);
  // 遍历模块，加载图片
  for (const path in modules) {
    const module = (await modules[path]()) as { default: string }; // 加载模块
    images.value.push(module.default); // 将图片路径添加到数组中
  }

  console.log("加载的图片路径:", images.value);
  // 初始化 IntersectionObserver
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          if (entry.target instanceof HTMLImageElement) {
            const img = entry.target;
            img.src = img.dataset.src as string;
          }
        }
      });
    },
    { threshold: 0.1 } // 当图片进入可视区域 10% 时触发
  );
  console.log(observer);
  console.log(imageRefs.value);
  // 监听所有图片元素
  imageRefs.value.forEach((el: any) => {
    const img = el.querySelector(".lazy-image");
    if (img) {
      observer.observe(img); // 开始监听
    }
  });
});
</script>
<template>
  <input type="text" v-model="username" />
  <button v-on:click="method1, method2">点击我</button>
  <button @click="method1, method2">安安</button>
  <div>我的{{ count }}</div>
  <div style="font-size: 20px">好的</div>
  <ul>
    <li>1</li>
    <li class="first">2</li>
    <li>3</li>
  </ul>
  <div class="button">按钮</div>

  <div>
    <h1>图片画廊</h1>
    <div class="image-container">
      <img
        v-for="(image, index) in images"
        :key="index"
        :src="image"
        :alt="`Image ${index + 1}`"
        class="image-item"
      />
    </div>
  </div>
  <h1>图片画廊（懒加载）</h1>
  <div class="image-container">
    <div
      v-for="(image, index) in images"
      :key="index"
      class="image-item"
      ref="imageRefs"
    >
      <img :data-src="image" :alt="`Image ${index + 1}`" class="lazy-image" />
    </div>
  </div>
</template>
<style scoped lang="scss">
$primary-color: #4caf50;
$font-size: 16px;

.button {
  background-color: $primary-color;
  font-size: $font-size;
}
li[style] {
  color: red;
}
.first + li {
  color: blue;
}
.first ~ li {
  color: rgb(235, 128, 5);
}
</style>
